package com.heima.bos.service;

import java.sql.Timestamp;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.heima.bos.dao.DaoInter;
import com.heima.bos.dao.DecidezoneDaoInter;
import com.heima.bos.dao.NoticebillDaoInter;
import com.heima.bos.dao.WorkbillDaoInter;
import com.heima.bos.domain.Decidezone;
import com.heima.bos.domain.Noticebill;
import com.heima.bos.domain.Staff;
import com.heima.bos.domain.User;
import com.heima.bos.domain.Workbill;
import com.heima.bos.utils.BOSUtils;
import com.heima.crm.service.CustomerService;
@Service
@Transactional
public class NoticebillService extends BaseService<Noticebill>{
	@Resource
	private NoticebillDaoInter noticebillDao;
	@Resource
	private CustomerService customerService;
	@Resource
	private DecidezoneDaoInter decidezoneDao;
	@Resource
	private WorkbillDaoInter workbillDao;
	/**
	 * 保存新的业务通知单
	 */
	public void save(Noticebill entity){
		//获取当前用户信息,并封装到noticebill中
		User user = (User) BOSUtils.getSession().getAttribute("user");
		noticebillDao.save(entity);//持久化对象
		//根据地址获取定区id
		String address = entity.getPickaddress();
		//调用代理对象根据地址获取定区id
		String decidedzone_id = customerService.findDecidezoneIdByAddress(address);
		if(decidedzone_id != null){
			
			//根据定区id获取staff
			Decidezone decidezone = decidezoneDao.findById(decidedzone_id);
			Staff staff = decidezone.getStaff();
			//将staff的信息封装到noticebill和workbill中
			entity.setStaff(staff);
			entity.setOrdertype("自动分单");
			//创建一个工单
			Workbill workbill = new Workbill();
			workbill.setAttachbilltimes(0);//追单次数
			workbill.setNoticebill(entity);//关联通知单
			workbill.setStaff(staff);//关联取派员
			workbill.setPickstate("未取件");//取件状态
			workbill.setBuildtime(new Timestamp(System.currentTimeMillis()));//创建工单时间
			workbill.setRemark(entity.getRemark());//备注
			workbill.setType("新");//工单类型 新 追 改  销
			//保存工单
			workbillDao.save(workbill);
			//封装其他信息
		}else{
			entity.setOrdertype("手动分单");
		}
	}

	@Override
	public DaoInter<Noticebill> getDao() {
		return noticebillDao;
	}
}
